package main

import (
	"hello/src/code/007gin_project/web/controller"
	"hello/src/code/007gin_project/web/model"
	"hello/src/code/007gin_project/web/utils"
	"os"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func main() {
	// 1. 初始化配置文件
	InitConfig()

	// 1.1 初始化mysql连接池
	model.InitDb()

	// 1.2 初始化引擎
	router := gin.Default()

	// 1.3 初始化session容器, 使用容器
	store := InitSession()
	router.Use(sessions.Sessions("MySession", store))

	// 2. 创建路由
	// 2.0 首页
	router.GET("/", controller.GetIndex)
	router.GET("/1", controller.GetIndex2)
	// 2.1 用户
	user := router.Group("/api/v1")
	{
		user.GET("/session", controller.GetSesion)
		user.GET("/imagecode/:uuid", controller.GetImageCd)
		user.POST("/login", controller.PostLogin)

		user.Use(utils.LoginFilter()) // 登陆完成后需要使用登陆的过滤器(之后的路由都不需要单独校验session)
		user.DELETE("/session", controller.DeleteSession)
		user.GET("/user", controller.GetUserInfo)
		user.PUT("/user/name", controller.PutUserInfo)
		user.POST("/user/avatar", controller.PostAvatar)
	}
	// 2.2 房源
	house := router.Group("/api/v1/house")
	{
		user.Use(utils.LoginFilter())
		house.GET("/", controller.GetHouses)
		user.GET("/getUser", controller.GetUserHouses)
		house.POST("/create", controller.PostHouses)
		house.POST("/:id/images", controller.PostHousesImage)
		house.GET("/:id", controller.GetHouseInfo)
		house.GET("/index", controller.GetHouseIndex)
	}

	// 3. 启动项目
	port := viper.GetString("server.port")
	if port != "" {
		panic(router.Run(":" + port))
	}
	panic(router.Run())
}

// 读取配置文件
func InitConfig() {
	workDir, _ := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/conf")
	if err := viper.ReadInConfig(); err != nil {
		panic("读取配置文件失败")
	}
}

// 初始化session
func InitSession() redis.Store {
	sessionSize := viper.GetInt("session.size")
	sessionStr := viper.GetString("session.host") + ":" + viper.GetString("session.port")
	store, _ := redis.NewStore(sessionSize, "tcp", sessionStr, "", []byte("secret"))
	return store
}
